var __extends = (this && this.__extends) || function(d, b) {
	for(var p in b)
		if(b.hasOwnProperty(p)) d[p] = b[p];

	function __() {
		this.constructor = d;
	}
	d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
define(["require", "exports", "core/BaseWidget.class", "widgets/CameraDebugger/Widget", "CsLibrary/CsHeatmap/CsHeatmap", "CsLibrary/TopologyAlgo/Topology", "CsLibrary/TopologyAlgo/Delaunay"],
	function(require, exports, BaseWidget, CameraDebugger, CsHeatmap, Topology, Delaunay) {
		"use strict";
		var BaseScene = (function(_super) {
			__extends(BaseScene, _super);

			function BaseScene() {
				var _this = _super.apply(this, arguments) || this;
				_this.baseClass = "widgets-basescene";
				_this.ScreenEventsManager = {
					"LEFT_CLICK": [],
					"MOUSE_MOVE": []
				}; //Scene屏幕事件管理器
				return _this;
			}
			BaseScene.prototype.startup = function() {
				this.addToDom({
					sceneDiv: this.config.sceneDiv
				});
				this.initScene();
				this.initCamera();
				this.LoadLayers();
				this.loadCameraDebugger();
				this.initEvent();

			};

			BaseScene.prototype.addToDom = function(data) {
				var htmlString = _.template(this.template)(data || {});
				$("#mainContainer_horizontal").html(htmlString);
			};

			//初始化场景对象
			BaseScene.prototype.initScene = function() {
				var scene = new Cesium.Viewer(this.config.sceneDiv, {
					animation: false,
					baseLayerPicker: false,
					geocoder: false,
					timeline: false,
					sceneModePicker: false,
					navigationHelpButton: false,
					infoBox: false,
					homeButton: false,
					maximumRenderTimeChange: Infinity,
					targetFrameRate: 15 //控制帧数
				});
				//取消相机变换的所有惯性
				scene.scene.screenSpaceCameraController.inertiaSpin = 0;
				scene.scene.screenSpaceCameraController.inertiaTranslate = 0;
				scene.scene.screenSpaceCameraController.inertiaZoom = 0;
				//去除版权信息
				scene._cesiumWidget._creditContainer.style.display = "none";
				this.scene = scene;
				this.AppX.runtimeConfig.scene = scene;
				this.initSceneEventControl();

				this.functionTest();
			};

			//Scene事件管理
			BaseScene.prototype.initSceneEventControl = function() {
				AppX.appConfig.SceneScreenEventsManager = this.ScreenEventsManager;
				var that = this;

				//鼠标点击对象时事件
				this.scene.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
					for(var index in that.ScreenEventsManager["LEFT_CLICK"]) {
						that.ScreenEventsManager["LEFT_CLICK"][index](movement);
					}
				}.bind(that), Cesium.ScreenSpaceEventType.LEFT_CLICK);

				//鼠标移动事件
				this.scene.screenSpaceEventHandler.setInputAction(onMouseMove.bind(this), Cesium.ScreenSpaceEventType.MOUSE_MOVE);

				function onMouseMove(movement) {
					for(var index in that.ScreenEventsManager["MOUSE_MOVE"]) {
						that.ScreenEventsManager["MOUSE_MOVE"][index](movement);
					}
				};
			};

			//初始化相机对象
			BaseScene.prototype.initCamera = function() {
				var extent = this.config.RectExtent;
				var cameraSetting = this.config.cameraSetting;
				this.scene.camera.position = Cesium.Cartesian3.fromElements(cameraSetting.position.x, cameraSetting.position.y, cameraSetting.position.z);
				this.scene.camera.direction = Cesium.Cartesian3.fromElements(cameraSetting.direction.x, cameraSetting.direction.y, cameraSetting.direction.z);
				this.scene.camera.up = Cesium.Cartesian3.clone(Cesium.Cartesian3.UNIT_Z);
				this.cameraChangedEvent = this.scene.camera.changed.addEventListener(function(percentage) {
					var degree = Cesium.Math.toDegrees(this.scene.camera.pitch);
					if(degree > -10) {
						this.scene.scene.screenSpaceCameraController.enableTilt = false;
					}
					var position = this.scene.scene.camera.position;
					var height = Cesium.Cartographic.fromCartesian(position).height;
					var globeheight = this.scene.scene.globe.getHeight(Cesium.Cartographic.fromCartesian(position));
				}.bind(this));
				var startMousePosition;
				var mousePosition;
				var scene = this.scene;
				var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
				handler.setInputAction(function(movement) {
					mousePosition = startMousePosition = Cesium.Cartesian3.clone(movement.position);
					handler.setInputAction(function(movement) {
						mousePosition = movement.endPosition;
						var y = mousePosition.y - startMousePosition.y;
						if(y >= 0) {
							scene.scene.screenSpaceCameraController.enableTilt = true;
						}
					}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
				}, Cesium.ScreenSpaceEventType.MIDDLE_DOWN);
			};

			//加载相机调试器
			BaseScene.prototype.loadCameraDebugger = function() {
				var cameraDebugger = new CameraDebugger({
					viewer: this.scene,
					camera: this.scene.Camera
				});
			};

			//加载图层
			BaseScene.prototype.LoadLayers = function() {
				this.loadTerrainLayer();
				this.loadImgLayer();
				this.loadAnnoLayer();
			};

			//加载地形图层
			BaseScene.prototype.loadTerrainLayer = function() {
				var terrainProvider = Cesium.createWorldTerrain();
				this.scene.terrainProvider = terrainProvider;
				this.scene.scene.globe.enableLighting = true;
			};
			//加载影像图层
			BaseScene.prototype.loadImgLayer = function() {
				var RectExtent = this.config.RectExtent;
				this.scene.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
					url: "http://{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
					layer: "img",
					style: "default",
					format: "image/jpeg",
					tileMatrixSetID: "w",
					show: false,
					subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
					maximumLevel: 16,
					credit: new Cesium.Credit("全球天地图影像地图服务"),
					// rectangle: Cesium.Rectangle.fromDegrees(RectExtent.xmin, RectExtent.ymin, RectExtent.xmax, RectExtent.ymax)
				}));
			};
			//加载注记图层
			BaseScene.prototype.loadAnnoLayer = function() {
				var RectExtent = this.config.RectExtent;
				this.scene.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
					url: "http://{s}.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg",
					layer: "cia",
					style: "default",
					format: "image/jpeg",
					tileMatrixSetID: "w",
					show: false,
					subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
					maximumLevel: 18,
					credit: new Cesium.Credit("全球天地图影像中文注记服务"),
					// rectangle: Cesium.Rectangle.fromDegrees(RectExtent.xmin, RectExtent.ymin, RectExtent.xmax, RectExtent.ymax)
				}));
			};

			BaseScene.prototype.initEvent = function() {
				this.ScreenEventsManager["LEFT_CLICK"]["createHeatmapPoints"] = function(e) {
					/* var pick1= new Cesium.Cartesian2(e.position.x,e.position.y);
                 var cartesian3 = this.scene.scene.globe.pick(this.scene.camera.getPickRay(pick1),this.scene.scene);
                 var cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
                 var lon =  Cesium.Math.toDegrees(cartographic.longitude);
                 var lat =  Cesium.Math.toDegrees(cartographic.latitude);*/
					// console.log("["+lon+","+lat+","+Math.random()*100+"],");
				}.bind(this);
			};

			BaseScene.prototype.CsHeatmapTest = function() {
				//test
				var points = [];
				for(var i in this.config.pointData)
					points.push({
						"lon": this.config.pointData[i][0],
						"lat": this.config.pointData[i][1],
						"value": this.config.pointData[i][2]
					});
				var csHeatmap = new CsHeatmap({
					points: points
				});
			};

			BaseScene.prototype.functionTest = function() {
				this.outPolygonTest();
				//this.DelaunayTriangulation();
				this.polygonSplitByPointTest();
			};

			BaseScene.prototype.outPolygonTest = function() {
				var points = [];
				for(var i in this.config.pointData) {
					var cartesian3 = Cesium.Cartesian3.fromDegrees(this.config.pointData[i][0], this.config.pointData[i][1]);
					var cartesian2 = Cesium.Cartesian2.fromCartesian3(cartesian3);
					points.push([cartesian2.x, cartesian2.y]);
				}
				var topology = new Topology();
				var polygonindex = topology.OutConvexPolgon(points);
				var index_list = polygonindex.map(function(item) {
					return item.index
				});
				var polygon_points = [];
				for(var i in index_list) {
					polygon_points.push(this.config.pointData[index_list[i]]);
				}

				//绘制点和标识
				for(var i in this.config.pointData) {
					var point = this.config.pointData[i];

					var label = {
						name: 'GSP',
						position: Cesium.Cartesian3.fromDegrees(point[0], point[1]),
						label: {
							text: i,
							font: '25px sans-serif',
							fillColor: Cesium.Color.BLUE,
							heightReference: Cesium.HeightReference.CLAMP_TO_GROUND

						}
					}
					this.scene.entities.add(label);

					var entity = {
						name: 'GSP',
						position: Cesium.Cartesian3.fromDegrees(point[0], point[1]),
						point: {
							color: Cesium.Color.WHITE,
							pixelSize: 20,
							heightReference: Cesium.HeightReference.CLAMP_TO_GROUND

						}
					}
					this.scene.entities.add(entity);
				}

				for(var i in polygon_points) {
					var point = polygon_points[i];
					var entity = {
						name: 'GSP',
						position: Cesium.Cartesian3.fromDegrees(point[0], point[1]),
						point: {
							color: Cesium.Color.RED,
							pixelSize: 40,
							heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
						}
					};
					this.scene.entities.add(entity);
				}

				var points2 = [];
				for(var i in polygonindex) {
					points2.push(polygonindex[i].coordinate);
				}

				this.ScreenEventsManager["LEFT_CLICK"]["test"] = function(e) {
					var pick1 = new Cesium.Cartesian2(e.position.x, e.position.y);
					var cartesian3 = this.scene.scene.globe.pick(this.scene.camera.getPickRay(pick1), this.scene.scene);
					var cartesian2 = Cesium.Cartesian2.fromCartesian3(cartesian3);
					var rel = topology.PolygonPointRel(points2, [cartesian2.x, cartesian2.y])
					alert(rel);
				}.bind(this);

			};

			BaseScene.prototype.DelaunayTriangulation = function() {
				var points = [];
				for(var i in this.config.pointData) {
					var cartesian3 = Cesium.Cartesian3.fromDegrees(this.config.pointData[i][0], this.config.pointData[i][1]);
					var cartesian2 = Cesium.Cartesian2.fromCartesian3(cartesian3);
					points.push([cartesian2.x, cartesian2.y]);
				}
				var delaunay = new Delaunay();
				delaunay.DelaunayTriangulation(points);
			};

			BaseScene.prototype.polygonSplitByPointTest = function() {
				var points = [];
				for(var i in this.config.pointData) {
					var cartesian3 = Cesium.Cartesian3.fromDegrees(this.config.pointData[i][0], this.config.pointData[i][1]);
					var cartesian2 = Cesium.Cartesian2.fromCartesian3(cartesian3);
					points.push([cartesian2.x, cartesian2.y]);
				}
				var topology = new Topology();
				var polygonindex = topology.OutConvexPolgon(points);
				var index_list = polygonindex.map(function(item) {
					return item.index
				});
				var polygon_points = [];
				for(var i in index_list) {
					polygon_points.push([this.config.pointData[index_list[i]][0],this.config.pointData[index_list[i]][1]]);
				}
				
				var delaunay = new Delaunay();
				var polygonD = new delaunay.Polygon();
				polygonD.constructByCoordinates(polygon_points);
				var pointD = new delaunay.Point();
				pointD.setCoordinate(this.config.pointData[0][0],this.config.pointData[0][1]);
				var split_polygons = delaunay.polygonSplitByPoint(polygonD,pointD);
				for(var i in split_polygons){
					var polygon = split_polygons[i];
					var points = polygon.getVertices();
					var coordinates = [];
					for(var j in points){
						var point = points[j];
						var coor = point.getCoordinate();
						var coordinates = coordinates.concat(coor);
						var entity ={
							name: 'Green extruded polygon',
							polygon: {
								hierarchy: Cesium.Cartesian3.fromDegreesArray(coordinates),
								extrudedHeight: 50.0,
								material: Cesium.Color.GREEN,
								closeTop: false,
								closeBottom: false
							}
                        };
                        this.scene.entities.add(entity);
					}
				}
			};

			return BaseScene;
		}(BaseWidget));
		return BaseScene;
	});